﻿using System.Linq;
using SuperSimpleWebshop.Common;
using SuperSimpleWebshop.Domain;
using SuperSimpleWebshop.Domain.Helpers;
using SuperSimpleWebshop.Domain.Interfaces;
using SuperSimpleWebshop.Domain.Repositories;
using umbraco;
using umbraco.BusinessLogic;
using umbraco.presentation.nodeFactory;
using System.Threading;

namespace SuperSimpleWebshop.Payment.SagePay
{
    public class SagePayPaymentResponseHandler : IPaymentResponseHandler
    {
        #region IPaymentResponseHandler Members
        IOrderRepository _OrderRepository = new OrderRepository();

        /// <summary>
        /// Gets the payment provider name
        /// </summary>
        /// <returns>Name of the payment provider</returns>
        public string GetName()
        {
            return "SagePay";
        }

        /// <summary>
        /// Handles the response
        /// </summary>
        public string HandlePaymentResponse()
        {
            // PayPal POSTS some values
            string paymentStatus = library.Request("Status");

            // Get identifier created with the RequestHandler
            string transactionId = library.Request("VPSTxId");

            // Match  identifier to order
            var order = this._OrderRepository.GetOrderByPaymentTransactionId(transactionId);

            // Check for match
            if (order != null)
            {
                // Get statusses from payment provider Response
                switch (paymentStatus)
                {
                    case "OK":
                        order.OrderInfo.Status = OrderStatus.Ready_for_Dispatch;
                        order.Save();

                        CreateAcknowlegeReceipt(order, "OK", "");

                        break;
                    case "MALFORMED":
                        order.OrderInfo.Status = OrderStatus.Payment_Failed;
                        order.OrderInfo.PaymentInfo.PaymentErrorMessage = library.Request("StatusDetail");
                        order.Save();

                        CreateAcknowlegeReceipt(order, "INVALID", "Malformed");

                        break;
                    case "INVALID":
                        order.OrderInfo.Status = OrderStatus.Payment_Failed;
                        order.OrderInfo.PaymentInfo.PaymentErrorMessage = library.Request("StatusDetail");
                        order.Save();

                        CreateAcknowlegeReceipt(order, "INVALID", "");

                        break;
                    case "ERROR":
                        order.OrderInfo.Status = OrderStatus.Payment_Failed;
                        order.OrderInfo.PaymentInfo.PaymentErrorMessage = library.Request("StatusDetail");
                        order.Save();

                        CreateAcknowlegeReceipt(order, "ERROR", "");

                        break;
                }

                order.Save();
            }

            return null;
        }
        #endregion

        #region acknowledge receipt
        public PaymentRequest CreateAcknowlegeReceipt(Order order, string status, string errorDetails)
        {
            var response = new PaymentRequest();

            // STATUS CAN BE:
            // - OK
            // - INVALID
            // - ERROR
            response.Parameters.Add("Status", status);

            var baseUrl = string.Format("http://{0}", library.GetCurrentDomains(Node.GetCurrent().Id).First().Name);
            baseUrl = baseUrl.Substring(0, baseUrl.LastIndexOf("/"));


            var oldUICulture = Thread.CurrentThread.CurrentUICulture;
            var oldCulture = Thread.CurrentThread.CurrentCulture;

            var shopAliasNode = ShopAliasHelper.GetAllShopAlias().Where(x => x.Name.ToLower() == order.OrderInfo.ShopAlias.Alias.ToLower()).FirstOrDefault();

            Thread.CurrentThread.CurrentCulture = shopAliasNode.CultureInfo;
            Thread.CurrentThread.CurrentUICulture = shopAliasNode.CultureInfo;

            var nodeId = DomainHelper.GetNodeIdForDocument("sswsOrderProcessNode", library.GetDictionaryItem("PaymentConfirmation"), order.OrderInfo.Alias);
            var cancelNodeId = DomainHelper.GetNodeIdForDocument("sswsOrderProcessNode", library.GetDictionaryItem("PaymentConfirmationFailed"), order.OrderInfo.Alias);

            Thread.CurrentThread.CurrentUICulture = oldUICulture;
            Thread.CurrentThread.CurrentCulture = oldCulture;
            
//            var nodeId = DomainHelper.GetNodeIdForDocument("sswsOrderProcessNode", library.GetDictionaryItem("PaymentConfirmation"), ShopAliasHelper.GetCurrentShopAlias());

            var returnUrl = string.Format("{0}{1}", baseUrl, library.NiceUrl(nodeId));
            response.Parameters.Add("RedirectURL", returnUrl);

            response.Parameters.Add("StatusDetail", errorDetails);

            return response;
        }
        #endregion
    }
}

